import {
  apiInterceptors,
  delMcp,
  pageMcp,
  updateMcp,
  connect_testMcp
} from '@/client/api';
import BlurredCard, { ChatButton, InnerDropdown } from '@/new-components/common/blurredCard';
import ConstructLayout from '@/new-components/layout/Construct';
import { BulbOutlined, DingdingOutlined, PlusOutlined, SearchOutlined, WarningOutlined } from '@ant-design/icons';
import { useDebounceFn, useRequest } from 'ahooks';
import { App, Button, Input, Modal, Pagination, Popover, Segmented, SegmentedProps, Select, Spin, Tag } from 'antd';
import copy from 'copy-to-clipboard';
import moment from 'moment';
import { useRouter } from 'next/router';
import { useCallback, useContext, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import CreateMcpModal from './components/create-mcp-modal/index';
import DetailMcp from './mcp_detail'
import { map } from 'lodash';

type ModalType = 'edit' | 'add';

export default function McpContent() {
  const router = useRouter();
  const { t } = useTranslation();
  const { message } = App.useApp();
  const [togglePage, setDetailPage ] = useState<boolean>(true);
  const [open, setOpen] = useState<boolean>(false);
  const [spinning, setSpinning] = useState<boolean>(false);
  const [mcps, setMcps] = useState([]);
  const [modalType, setModalType] = useState<ModalType>('add');
  const [filterValue, setFilterValue] = useState('');
  const [activeKey, setActiveKey] = useState<TabKey>(-1);

  // 分页信息
  const totalRef = useRef<{
    current_page: number;
    total_count: number;
    total_page: number;
  }>();

  const items: SegmentedProps['options'] = [
    {
      value: -1,
      label: t('All'),
    },
    {
      value: 1,
      label: t('published'),
    },
    {
      value: 0,
      label: t('unpublished'),
    },
  ];

  const handleCreate = (data) => {
    if(data.id){
      localStorage.setItem('new_mcp_info', JSON.stringify(data));
      setModalType('edit');
    }else{
      localStorage.setItem('new_mcp_info', JSON.stringify({type:'sse'}));
      setModalType('add');
    }
    
    setOpen(true);
  };

  const handleTabChange = (activeKey: string) => {
    setActiveKey(activeKey as TabKey);
  };

  const handleEdit = (mcp: any) => {
    localStorage.setItem('new_mcp_info', JSON.stringify({ ...mcp, isEdit: true }));
    setDetailPage(false)
  };


  const getListFiltered = useCallback(() => {
    const params = { keyword: filterValue }
    if(activeKey >-1){
      params.state = activeKey
    }else{
      delete params.state
    }
    initData(params);
  }, [activeKey,filterValue]);

  // 发布或下架
  const { run: operate } = useRequest(
    async (mcp:any) => {
      const params = {
        id: mcp.id,
        name: mcp.name,
        desc: mcp.desc,
        type: mcp.type,
        server_url: mcp.server_url,
        server_headers: mcp.server_headers,
        creator: mcp.creator,
        state: mcp.state == 1 ? 0 : 1,
        script: mcp?.script || '',
        args: mcp?.args || '',
        env: mcp?.env || '',        
      }
      return await apiInterceptors(updateMcp(params));
    },
    {
      manual: true,
      onSuccess: data => {
        if (data[2]?.success) {
          message.success('操作成功');
        }
        getListFiltered();
      },
    },
  );
  // 连接测试 地址
  const { run: connectTest } = useRequest(
    async (mcp:any) => {
      const params = {
        id: mcp.id,
        name: mcp.name,
        desc: mcp.desc,
        type: mcp.type,
        server_url: mcp.server_url,
        server_headers: mcp.server_headers,
        creator: mcp.creator,
        state: mcp.state,
        script: mcp?.script || '',
        args: mcp?.args || '',
        env: mcp?.env || '',          
      }
      return await apiInterceptors(connect_testMcp(params));
    },
    {
      manual: true,
      onSuccess: data => {
        if (data[2]?.success && data[2]?.data) {
          message.success('连接成功');
        }else{
          message.error(data[2]?.message || '连接已失效');
        }      
      },
    },
  );

  const initData = useDebounceFn(
    async params => {
      setSpinning(true);
      const obj: any = {
        page: 1,
        page_size: 12,
        ...params
      };
      const [error, data] = await apiInterceptors(pageMcp(obj));
      if (error) {
        setSpinning(false);
        return;
      }
      if (!data) return;
      setMcps(data?.items || []);
      totalRef.current = {
        current_page: data?.page || 1,
        total_count: data?.total_count || 0,
        total_page: data?.total_page || 0,
      };
      setSpinning(false);
    },
    {
      wait: 500,
    },
  ).run;

  const showDeleteConfirm = (auth) => {
    Modal.confirm({
      title: t('Tips'),
      icon: <WarningOutlined />,
      content: t('want_delete'),
      okText: t('verify'),
      okType: 'danger',
      cancelText: t('cancel'),
      async onOk() {
        await apiInterceptors(delMcp({ id: auth.id }));
        getListFiltered();
      },
    });
  };

  const onSearch = async (e: any) => {
    const v = e.target.value;
    setFilterValue(v);
  };

  useEffect(() => {
    getListFiltered();
  }, [getListFiltered]);


  return (
    <ConstructLayout>
      {togglePage ? (
        <Spin spinning={spinning}>
          <div className='h-screen w-full p-4 md:p-6 overflow-y-auto'>
            <div className='flex justify-between items-center mb-6'>
              <div className='flex items-center gap-4'>
                <Segmented
                    className='backdrop-filter h-10 backdrop-blur-lg bg-white bg-opacity-30 border border-white rounded-lg shadow p-1 dark:border-[#6f7f95] dark:bg-[#6f7f95] dark:bg-opacity-60'
                    options={items as any}
                    onChange={handleTabChange}
                    value={activeKey}
                  />
                <Input
                  variant='filled'
                  value={filterValue}
                  prefix={<SearchOutlined />}
                  placeholder={t('please_enter_the_keywords')}
                  onChange={onSearch}
                  onPressEnter={onSearch}
                  allowClear
                  className='w-[230px] h-[40px] border-1 border-white backdrop-filter backdrop-blur-lg bg-white bg-opacity-30 dark:border-[#6f7f95] dark:bg-[#6f7f95] dark:bg-opacity-60'
                />
              </div>

              <Button
                className='border-none text-white bg-button-gradient flex items-center'
                icon={<PlusOutlined className='text-base' />}
                onClick={(handleCreate)}
              >
                {t('create_mcp')}
              </Button>
            </div>
            <div className=' w-full flex flex-wrap pb-12 mx-[-8px]'>
              {mcps.map(item => {
                return (
                  <BlurredCard
                    key={item.id}
                    code={item.id}
                    name={item.name}
                    description={item.desc}
                    RightTop={
                      <div className='flex items-center gap-2'>
                        <InnerDropdown
                          menu={{
                            items: item.state ? [
                              {
                                key: 'edit',
                                label: (
                                  <span
                                    onClick={e => {
                                      e.stopPropagation();
                                      handleCreate(item);
                                    }}
                                  >
                                    {t('Edit')}
                                  </span>
                                ),
                              },
                              {
                                key: 'unPublish',
                                label: (
                                  <span
                                    onClick={e => {
                                      e.stopPropagation();
                                      operate(item);
                                    }}
                                  >
                                    下架
                                  </span>
                                ),
                              },
                              {
                                key: 'connect',
                                label: (
                                  <span
                                    onClick={e => {
                                      e.stopPropagation();
                                      connectTest(item);
                                    }}
                                  >
                                    校验
                                  </span>
                                ),
                              }
                            ]: [
                              {
                                key: 'unPublish',
                                label: (
                                  <span
                                    onClick={e => {
                                      e.stopPropagation();
                                      operate(item);
                                    }}
                                  >
                                    发布
                                  </span>
                                ),
                              },
                              {
                                key: 'edit',
                                label: (
                                  <span
                                    onClick={e => {
                                      e.stopPropagation();
                                      handleCreate(item);
                                    }}
                                  >
                                    {t('Edit')}
                                  </span>
                                ),
                              },
                              {
                                key: 'connect',
                                label: (
                                  <span
                                    onClick={e => {
                                      e.stopPropagation();
                                      connectTest(item);
                                    }}
                                  >
                                    校验
                                  </span>
                                ),
                              },
                              {
                                key: 'del',
                                label: (
                                  <span
                                    className='text-red-400'
                                    onClick={e => {
                                      e.stopPropagation();
                                      showDeleteConfirm(item);
                                    }}
                                  >
                                    {t('Delete')}
                                  </span>
                                ),
                              },
                            ],
                          }}
                        />
                      </div>
                    }
                    Tags={
                      <div>
                          <Tag color={item.state ==1?"green":"orange"}>{item.state===1?'已发布':'未发布'}</Tag>     
                          <Tag color="purple">{item.type==1?"MCP-streamableHttp":item.type==2?'MCP-STDIO':"MCP-SSE"}</Tag>                         
                      </div>
                    }
                    rightTopHover={false}
                    LeftBottom={
                      <div className='flex gap-2 text-[#828282]'>
                        <span>{item.creator}</span>
                        <span>•</span>
                        {item?.update_datetime && <span>{moment(item?.update_datetime).fromNow() + ' ' + t('update')}</span>}
                      </div>
                    }
                    onClick={() => {
                      handleEdit(item);
                    }}
                    scene=""              
                  />
                );
              })}
              <div className='w-full flex justify-end shrink-0 pb-12'>
                <Pagination
                  total={totalRef.current?.total_count || 0}
                  pageSize={12}
                  current={totalRef.current?.current_page}
                  onChange={async (page, _page_size) => {
                    await initData({ page });
                  }}
                />
              </div>
            </div>

            {open && (
              <CreateMcpModal
                open={open}
                onCancel={() => {
                  setOpen(false);
                }}
                refresh={initData}
                type={modalType}            
              />
            )}
          </div>
        </Spin>) : 
        (<DetailMcp setDetailPage={setDetailPage} />
      )}
    </ConstructLayout>
  );
}


